package com.mmf.ancientcostume.fragment.user;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.mmf.ancientcostume.MyApplication;
import com.mmf.ancientcostume.R;
import com.mmf.ancientcostume.activity.ImagePreviewActivity;
import com.mmf.ancientcostume.activity.SelAddressActivity;
import com.mmf.ancientcostume.adapter.home.ReleaseInfoImageAdapter;
import com.mmf.ancientcostume.base.fragment.BaseFragment;
import com.mmf.ancientcostume.common.utils.DipUtil;
import com.mmf.ancientcostume.model.StaticData;
import com.mmf.ancientcostume.other.zhy.imageloader.MyAdapter;
import com.mmf.ancientcostume.other.zhy.imageloader.SelPhotoActivity;
import com.mmf.ancientcostume.presenter.imp.release.ReleasePresenterImp;
import com.mmf.ancientcostume.view.BaseView;
import com.mmf.ancientcostume.widget.JumpPreviewActivityListener;
import com.mmf.ancientcostume.widget.ReleaseAdapterInterface;
import com.mmf.ancientcostume.widget.SpaceItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by MMF on 2017-07-13.
 * 添加发布信息界面
 */

public class ReleaseFragment extends BaseFragment<ReleasePresenterImp, ReleaseFragment> implements BaseView {
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.lyt_address)
    LinearLayout lytAddress;
    @BindView(R.id.ed_detail_address)
    EditText edDetailAddress;
    @BindView(R.id.tv_sel)
    TextView tvSel;
    @BindView(R.id.rv_preview_img)
    RecyclerView rvPreviewImg;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_describe)
    EditText etDescribe;
    @BindView(R.id.ed_rental)
    EditText edRental;
    @BindView(R.id.ed_deposit)
    EditText edDeposit;
    @BindView(R.id.tv_release)
    TextView tvRelease;
    @BindView(R.id.rv_detail_img)
    RecyclerView rvDetailImg;
    private int TOP_TYPE = 1;
    private int BOTTOM_TYPE = 2;
    private List<String> imgUrls = new ArrayList<>();
    private ArrayList<String> imgUrlsDetail = new ArrayList<>();
    private ReleaseInfoImageAdapter adapter;
    private ReleaseInfoImageAdapter adapterDetail;
    private String province;    //省份
    private String city;         //城市
    private String district;    //地区
    private String street;       //街道
    private BroadcastReceiver receiver;

    public int getLayout() {
        return R.layout.fragment_release_info;
    }

    public void init() {
        setAdapter();
        setAddress();
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                setAddress();
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(StaticData.LOCATION_SUCCESS_ACTION);
        getActivity().registerReceiver(receiver, filter);
    }

    public void setAddress() {
        if (MyApplication.getInstance().getCurrlocation() != null) {
            BDLocation bdLocation = MyApplication.getInstance().getCurrlocation();
            province = bdLocation.getProvince();
            city = bdLocation.getCity();
            district = bdLocation.getDistrict();
            street = bdLocation.getStreet();
            tvAddress.setText(province + city + district);
        } else {
            MyApplication.getInstance().startLocation();
        }
    }

    @Override
    protected ReleasePresenterImp getPresenter() {
        return new ReleasePresenterImp();
    }

    @OnClick({R.id.tv_sel, R.id.tv_release, R.id.lyt_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_sel:
                jumpSelPhoto(StaticData.RELEASE_SEL_IMAGE);
                break;
            case R.id.tv_release:
                if (presenter.check(getData())) {
                    presenter.insertDetail(getImgRequestBody(), getData());
                }
                break;
            case R.id.lyt_address:
                Intent intent1 = new Intent(getActivity(), SelAddressActivity.class);
                startActivityForResult(intent1, StaticData.RELEASE_SEL_ADDRESS);
                break;
        }
    }

    /**
     * 跳转搭配选择图片的界面
     *
     * @param requestCode 回调的参数
     */
    private void jumpSelPhoto(int requestCode) {
        Intent intent = new Intent(getActivity(), SelPhotoActivity.class);
        if (requestCode == StaticData.RELEASE_SEL_IMAGE) {
            intent.putExtra("maxNum", 5 - imgUrls.size());
        } else {
            intent.putExtra("maxNum", 9 - imgUrlsDetail.size());
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 获取发布的界面信息
     *
     * @return
     */
    private Map<String, Object> getData() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", etTitle.getText().toString());
        map.put("describe", etDescribe.getText().toString());
        map.put("rental", edRental.getText().toString());
        map.put("deposit", edDeposit.getText().toString());
        map.put("province", province);
        map.put("city", city);
        map.put("district", district);
        map.put("address", province + city + district);
        map.put("userId", MyApplication.getUserId());
        return map;
    }

    /**
     * 获取发布的图片信息
     *
     * @return
     */
    private Map<String, RequestBody> getImgRequestBody() {
        Map<String, RequestBody> bodyMap = new HashMap<String, RequestBody>();
        //添加详情的预览图片包括商品列表的封面图片
        if (imgUrls.size() > 0) {
            for (int i = 0; i < imgUrls.size(); i++) {
                File file = new File(imgUrls.get(i).trim());
                //如果是顶部的添加图片那么设置第一张为封面的图片
                if (i == 0) {
                    bodyMap.put("0" + "\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
                } else {
                    bodyMap.put(1 + "\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
                }
            }
        }
        //添加详情的图片数据
        if (imgUrlsDetail.size() > 0) {
            for (int i = 0; i < imgUrlsDetail.size(); i++) {
                File file = new File(imgUrlsDetail.get(i).trim());
                bodyMap.put(2 + "\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
            }
        }
        return bodyMap;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取选择的图片的真实路劲
        if (requestCode == StaticData.RELEASE_SEL_IMAGE) {
            imgUrls.addAll(data.getStringArrayListExtra("imgUrls"));
            adapter.setItems(imgUrls);
        } else if (requestCode == StaticData.RELEASE_SEL_DETAIL_IMAGE) {
            imgUrlsDetail.addAll(data.getStringArrayListExtra("imgUrls"));
            adapterDetail.setItems(imgUrlsDetail);
        } else if (requestCode == StaticData.RELEASE_SEL_ADDRESS) {
            province = data.getStringExtra("province");
            city = data.getStringExtra("city");
            district = data.getStringExtra("district");
            tvAddress.setText(province + city + district);
        }
    }

    private void setAdapter() {
        //将RecyclerView设置成gridview的样式 每行显示4个
        GridLayoutManager mgr = new GridLayoutManager(getActivity(), 4);
        int space = DipUtil.dip2px(getActivity(), 4);
        //设置显示的适配器
        adapter = new ReleaseInfoImageAdapter(getActivity(), 4);
        adapter.setItems(imgUrls);
        rvPreviewImg.setLayoutManager(mgr);
        //设置RecyclerView每个item的间距
        rvPreviewImg.addItemDecoration(new SpaceItemDecoration(space, 4));
        rvPreviewImg.setAdapter(adapter);
        adapter.setReleaseAdapterInterface(new ReleaseAdapterInterface() {
            @Override
            public void jumpSelImage() {
                jumpSelPhoto(StaticData.RELEASE_SEL_IMAGE);
            }

            @Override
            public void jump(int position, List<String> itemList) {
                Intent intent = new Intent(getActivity(), ImagePreviewActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("selPosition", position);
                intent.putStringArrayListExtra("imgUrls", (ArrayList<String>) imgUrls);
                intent.putStringArrayListExtra("imgPath", (ArrayList<String>) itemList);
                startActivityForResult(intent, 1);
            }
        });
        //设置显示的适配器
        adapterDetail = new ReleaseInfoImageAdapter(getActivity(), 9);
        adapterDetail.setItems(imgUrls);
        GridLayoutManager mgr1 = new GridLayoutManager(getActivity(), 4);
        rvDetailImg.setLayoutManager(mgr1);
        //设置RecyclerView每个item的间距
        rvDetailImg.addItemDecoration(new SpaceItemDecoration(space, 4));
        rvDetailImg.setAdapter(adapterDetail);
        adapterDetail.setReleaseAdapterInterface(new ReleaseAdapterInterface() {
            @Override
            public void jumpSelImage() {
                jumpSelPhoto(StaticData.RELEASE_SEL_DETAIL_IMAGE);
            }

            @Override
            public void jump(int position, List<String> itemList) {
                Intent intent = new Intent(getActivity(), ImagePreviewActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("selPosition", position);
                intent.putStringArrayListExtra("imgUrls", (ArrayList<String>) imgUrlsDetail);
                intent.putStringArrayListExtra("imgPath", (ArrayList<String>) itemList);
                startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    public void onSuccess(Object object) {

    }

    @Override
    public void onError(String object) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(receiver);
    }

}
